package net.zjitc.dao.impl;

import net.zjitc.dao.CartItemDao;
import net.zjitc.domain.CartItem;
import net.zjitc.domain.Product;
import net.zjitc.domain.User;
import net.zjitc.utils.C3P0Utils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 2 * @Author: 洪瑶
 * 3 * @Date: 2018/11/22 9:07
 * 4
 */
public class CartItemDaoImpl implements CartItemDao{
    QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());

    @Override
    public void addCart(CartItem cartItem) throws SQLException {
        String sql = "insert into cartitem(uid,pid,quantity)values(?,?,?)";
        runner.update(sql,new Object[]{cartItem.getUser().getUid(),cartItem.getProduct().getPid(),cartItem.getQuantity()});
    }

    @Override
    public List<CartItem> findByuid(int uid) throws Exception{
        String sql = "select * from cartitem where uid = ?";
        List<CartItem> cartItems = runner.query(sql, new BeanListHandler<CartItem>(CartItem.class), uid);
        return cartItems;
    }

    @Override
    public CartItem findById(int uid, int pid) throws SQLException {
        String sql = "select * from cartitem where uid = ? and pid = ?";
        CartItem cartItem = runner.query(sql,new BeanHandler<CartItem>(CartItem.class), uid, pid);
        return cartItem;
    }

    @Override
    public void update(CartItem cartItem) throws SQLException {
        String sql = "update cartitem set quantity = ? where uid = ? and pid = ?";
        runner.update(sql,new Object[]{cartItem.getQuantity(),cartItem.getUid(),cartItem.getPid()});
    }

    @Override
    public void delete(int cartid) throws SQLException {
        String sql = "delete from cartitem where cartid = ?";
        runner.update(sql,cartid);
    }

    @Override
    public void deleteAll(int uid) throws SQLException {
        String sql = "delete from cartitem where uid = ?";
        runner.update(sql,uid);
    }
}
